#include <iostream>
#include <unistd.h>
#include <vector>
#include <queue>
#include <pthread.h>
using namespace std;

const static int defaultNum = 5;
struct ThreadInfo
{
    string name;
    pthread_t tid;
};

template <class T>
class ThreadPool
{
public:
    void lock()
    {
        pthread_mutex_lock(&_task_mutex);
    }

    void unlock()
    {
        pthread_mutex_unlock(&_task_mutex);
    }

    void wakeup()
    {
        pthread_cond_signal(&_cond);
    }

    void threadSleep()
    {
        pthread_cond_wait(&_cond, &_task_mutex);
    }

    string getThreadName(pthread_t tid)
    {
        for (auto thread : _threads)
        {
            if (tid == thread.tid)
            {
                return thread.name;
            }
        }
        return "No exist.";
    }

private:
    ThreadPool(const ThreadPool<T> &) = delete;
    const ThreadPool &operator=(const ThreadPool<T> &) = delete;

    ThreadPool(int num = defaultNum)
        : _threads(num)
    {
        pthread_mutex_init(&_task_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_task_mutex);
        pthread_cond_destroy(&_cond);
    }

public:
    static ThreadPool<T> *getInstance(int num = defaultNum)
    {
        if(_tp==nullptr){//避免每次调用getInstance()时都进行加锁 / 解锁操作（加锁是开销较大的操作）
            pthread_mutex_lock(&_init_mutex);
            if (_tp == nullptr)
            {
                _tp = new ThreadPool<T>(num);
            }
            pthread_mutex_unlock(&_init_mutex);
        }

        return _tp;
    }

    static void *handler(void *args) // 线程循环加锁检测队列。若为空则阻塞等待；若有任务则取出解锁后执行
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        while (true)
        {
            tp->lock();
            while (tp->_tasks.empty())
            {
                tp->threadSleep();
            }
            T t = tp->_tasks.front();
            tp->_tasks.pop();
            tp->unlock();
            t.run();
            cout << tp->getThreadName(pthread_self()) << " , result:" << t.getResult() << endl;
        }
    }

    void start() // 预先创建一些线程
    {
        for (int i = 0; i < _threads.size(); ++i)
        {
            _threads[i].name = "thread-" + to_string(i + 1);
            pthread_create(&(_threads[i].tid), nullptr, handler, this);
        }
    }

    void push(const T &t) // 外部通过 push 向队列添加任务，添加后唤醒一个阻塞的线程处理任务。
    {
        lock();
        _tasks.push(t);
        wakeup();
        unlock();
    }

    T pop()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }

private:
    vector<ThreadInfo> _threads;
    queue<T> _tasks;

    pthread_mutex_t _task_mutex;
    pthread_cond_t _cond;

    static ThreadPool *_tp;
    static pthread_mutex_t _init_mutex;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::_init_mutex = PTHREAD_MUTEX_INITIALIZER;